package com.xidian.zhiancloud.controller.ledgerManagerment.relatedPart;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xidian.zhiancloud.controller.base.BaseController;
import com.xidian.zhiancloud.dto.ResultDTO;
import com.xidian.zhiancloud.enums.GeneralResponseEnums;
import com.xidian.zhiancloud.model.RelatedPartyDoc;
import com.xidian.zhiancloud.model.RelatedPartyPeopleDoc;
import com.xidian.zhiancloud.qo.ledgerManagerment.relatedParty.RelatedPartyPeopleDocQO;
import com.xidian.zhiancloud.service.ledgerManager.relatedPart.RelatedPartyDocService;
import com.xidian.zhiancloud.service.ledgerManager.relatedPart.RelatedPartyPeopleDocService;
import com.xidian.zhiancloud.vo.ledgerManagerment.relatedParty.RelatedPartyPeopleDocVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * 台账管理 相关方管理 相关方人员管理
 *
 * @Author: Summerless
 * @Date: 2020/11/9 11:28
 */
@RestController
@RequestMapping("/RelatedPartyPeopleDoc")
public class RelatedPartyPeopleDocController extends BaseController {
    @Autowired
    private RelatedPartyPeopleDocService relatedPartyPeopleDocService;
    @Autowired
    private RelatedPartyDocService relatedPartyDocService;

    /**
     * 增加一个相关方人员对象
     *
     * @param relatedPartyPeopleDoc 相关方人员对象
     * @return 是否添加成功
     */
    @PostMapping("/add")
    public ResultDTO<Boolean> add(RelatedPartyPeopleDoc relatedPartyPeopleDoc) {
        relatedPartyPeopleDoc.setCreatorId(getSessionUserid());
        relatedPartyPeopleDoc.setCompanyId(getSessionUserid());
        relatedPartyPeopleDoc.setCreateTime(new Date(System.currentTimeMillis()));
        Boolean res = relatedPartyPeopleDocService.save(relatedPartyPeopleDoc);
        return ResultDTO.successOf(res, GeneralResponseEnums.SUCCESS);
    }

    /**
     * 根据id获取相关方人员对象
     *
     * @param id 相关方人员对象的id
     * @return 相关方人员对象
     */
    @GetMapping("/getById")
    public ResultDTO<RelatedPartyPeopleDocVO> getById(@RequestParam("id") Long id) {
        return ResultDTO.successOf(relatedPartyPeopleDocService.getVOById(id), GeneralResponseEnums.SUCCESS);
    }

    /**
     * 根据id列表删除相关方人员对象
     *
     * @param ids id列表
     * @return 是否删除成功
     */
    @PostMapping("/deleteByIds")
    public ResultDTO<Boolean> deleteByIds(Long[] ids) {
        Boolean res = relatedPartyPeopleDocService.removeByIds(Arrays.asList(ids));
        return ResultDTO.successOf(res, GeneralResponseEnums.SUCCESS);
    }

    /**
     * 修改相关方人员对象
     *
     * @param relatedPartyPeopleDoc 相关方人员对象
     * @return 是否修改成功
     */
    @PostMapping("/patchById")
    public ResultDTO<Boolean> patchById(RelatedPartyPeopleDoc relatedPartyPeopleDoc) {
        relatedPartyPeopleDoc.setCompanyId(null);
        relatedPartyPeopleDoc.setCreatorId(null);
        relatedPartyPeopleDoc.setCreateTime(null);
        Boolean res = relatedPartyPeopleDocService.updateById(relatedPartyPeopleDoc);
        return ResultDTO.successOf(res, GeneralResponseEnums.SUCCESS);
    }

    /**
     * 列表查询
     *
     * @param relatedPartyPeopleDocQO 查询参数
     * @return 相关方人员对象列表
     */
    @GetMapping("/getListByQO")
    public ResultDTO<IPage<RelatedPartyPeopleDocVO>> getListByQO(RelatedPartyPeopleDocQO relatedPartyPeopleDocQO) {
        if (relatedPartyPeopleDocQO.getCurrent() == null || relatedPartyPeopleDocQO.getSize() == null) {
            return ResultDTO.errorOf(GeneralResponseEnums.REQUEST_ERROR);
        }
        relatedPartyPeopleDocQO.setCompanyId(getSessionUserid());
        return ResultDTO.successOf(relatedPartyPeopleDocService.getListByQO(relatedPartyPeopleDocQO), GeneralResponseEnums.SUCCESS);
    }

    /**
     * 导出
     *
     * @param response
     * @param ids      id列表
     * @throws IOException
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response, Long[] ids) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("相关方人员档案导出", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        List<RelatedPartyPeopleDoc> list = relatedPartyPeopleDocService.listByIds(Arrays.asList(ids));
        List<RelatedPartyPeopleDocVO> ans = new LinkedList<>();
        list.forEach(o -> {
            RelatedPartyPeopleDocVO vo = new RelatedPartyPeopleDocVO();
            BeanUtils.copyProperties(o, vo);
            RelatedPartyDoc relatedPartyDoc = relatedPartyDocService.getById(vo.getBelongRelatedPartyId());
            vo.setBelongRelatedPartyName(relatedPartyDoc == null ? "该第三方已被删除" : relatedPartyDoc.getName());
            ans.add(vo);
        });
        EasyExcel.write(response.getOutputStream(), RelatedPartyPeopleDocVO.class).sheet("模板").doWrite(ans);
    }

    /**
     * 导入
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public ResultDTO<Boolean> upload(@RequestParam("file") MultipartFile file) throws IOException {
        List<RelatedPartyPeopleDocVO> list = EasyExcel.read(file.getInputStream()).head(RelatedPartyPeopleDocVO.class).sheet().doReadSync();
        List<RelatedPartyPeopleDoc> ans = new LinkedList<>();
        list.forEach(vo -> {
            RelatedPartyPeopleDoc doc = new RelatedPartyPeopleDoc();
            BeanUtils.copyProperties(vo, doc);
            doc.setCompanyId(getSessionUserCompanyId());
            doc.setCreatorId(getSessionUserid());
            doc.setCreateTime(new Date(System.currentTimeMillis()));
            LambdaQueryWrapper<RelatedPartyDoc> query = Wrappers.<RelatedPartyDoc>lambdaQuery();
            query.eq(RelatedPartyDoc::getName, vo.getBelongRelatedPartyName());
            RelatedPartyDoc one = relatedPartyDocService.getOne(query);
            if (one != null) {
                doc.setBelongRelatedPartyId(one.getId());
                ans.add(doc);
            }
        });
        list.forEach(System.out::println);
        Boolean res = relatedPartyPeopleDocService.saveBatch(ans);
        return ResultDTO.successOf(res, GeneralResponseEnums.SUCCESS);
    }
}
